import { Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { Logs } from './entities/logs.entity';
import { Repository } from 'typeorm';
import { GetUserDto } from './dto/get-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    public readonly userRepository: Repository<User>,
    @InjectRepository(Logs)
    private readonly logsRepository: Repository<Logs>,
  ) {}
  async create(createUserDto: CreateUserDto) {
    const existingUser = await this.userRepository.findOne({
      where: { username: createUserDto.username },
    });
    if (existingUser) {
      throw new Error('Username already exists'); // 或自定义异常[3](@ref)
    }

    // 创建并保存用户
    const user = this.userRepository.create(createUserDto);
    return this.userRepository.save(user);
  }

  async findAll(query: GetUserDto) {
    try {
      const { limit, page, username, gender, email } = query;
      // const pageNumber = Math.max(Number(page) || 1, 1); // page是页码，默认为1
      const limitNumber = limit || 10; // limit是每页显示的数量，默认为10

      const skip = (page || 1 - 1) * limitNumber;
      const data = await this.userRepository.find({
        select: {
          id: true,
          username: true,
          email: true,
          profile: {
            gender: true,
          },
        },
        relations: {
          profile: true,
          roles: true,
        },
        where: {
          email,
          username,
          profile: {
            gender,
          },
        },
        take: limitNumber,
        skip: skip,
      });
      // const queryBuilder = this.userRepository
      //   .createQueryBuilder('user')
      //   .innerJoinAndSelect('user.profile', 'profile')
      //   .innerJoinAndSelect('user.roles', 'roles');

      // if (username) {
      //   queryBuilder.where('user.username = :username', { username });
      // } else {
      //   queryBuilder.where('user.username IS NOT NULL');
      // }
      // if (email) {
      //   queryBuilder.andWhere('user.email = :email', { email });
      // } else {
      //   queryBuilder.andWhere('user.email IS NOT NULL');
      // }
      // if (gender) {
      //   queryBuilder.andWhere('profile.gender = :gender', { gender });
      // } else {
      //   queryBuilder.andWhere('profile.gender IS NOT NULL');
      // }

      // const data = queryBuilder.getMany();
      return {
        code: 200,
        msg: '获取成功',
        data,
      };
    } catch (error) {
      console.error('Error in findAll:', error);
      return {
        code: 500,
        msg: error || '获取失败',
      };
    }
  }

  findOne(id: number) {
    return this.userRepository.findOne({ where: { id } });
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    const user = this.userRepository.findOne({ where: { id } });
    console.log(user);
    return this.userRepository.update(id, updateUserDto);
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }
  async findLogs(id: number) {
    const user = await this.userRepository.findOne({ where: { id } });
    console.log(user);
    return this.logsRepository.find({
      where: { user: { id } }, // 通过嵌套条件查询
      relations: ['user'], // 按需加载关联的 User 对象
    });
  }

  logsCount(id: number) {
    return this.logsRepository
      .createQueryBuilder('logs')
      .select('logs.statusCode')
      .addSelect('COUNT(logs.statusCode)', 'count')
      .leftJoinAndSelect('logs.user', 'user')
      .where('user.id = :id', { id })
      .groupBy('logs.statusCode')
      .getRawMany();
  }
}
